# mysql_val.py
import threading
import pymysql
from queue import Queue


def try_connect(host, port, user, password, queue):
    """独立的连接测试函数"""
    try:
        conn = pymysql.connect(
            host=host,
            port=int(port),
            user=user,
            password=password,
            connect_timeout=3
        )
        conn.close()
        queue.put({
            "host": host,
            "port": port,
            "user": user,
            "password": password
        })
    except Exception as e:
        pass


def val_mysql(host, port, userfile, passwdfile):
    """主验证函数"""
    # 文件内容读取
    users = userfile.getvalue().decode().splitlines()
    passwords = passwdfile.getvalue().decode().splitlines()

    # 创建线程安全队列
    result_queue = Queue()
    threads = []

    # 创建并启动线程
    for user in users:
        for password in passwords:
            t = threading.Thread(
                target=try_connect,  # 正确引用已定义的函数
                args=(host, port, user.strip(), password.strip(), result_queue)
            )
            t.start()
            threads.append(t)

    # 等待线程完成
    for t in threads:
        t.join()

    # 收集结果
    final_result = {
        "host": [],
        "port": [],
        "user": [],
        "password": []
    }
    while not result_queue.empty():
        item = result_queue.get()
        for key in final_result:
            final_result[key].append(item[key])

    return final_result